package com.zhou.org.common;

import com.zhou.util.StringTool;
import com.zhou.org.dao.SysMenu;
import com.zhou.org.model.MetaVo;
import com.zhou.org.model.RouterVo;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author lang.zhou
 * @since 2023/2/14 14:17
 */
public class MenuUtil {

    /**
     * 根据父节点的ID获取所有子节点
     *
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public static List<SysMenu> getChildPerms(List<SysMenu> list, int parentId)
    {
        List<SysMenu> returnList = new ArrayList<SysMenu>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    public static List<SysMenu> buildMenuTree(List<SysMenu> menus)
    {
        List<SysMenu> returnList = new ArrayList<>();
        List<Long> tempList = menus.stream().map(SysMenu::getMenuId).collect(Collectors.toList());
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端路由所需要的菜单
     *
     * @param menus 菜单列表
     * @return 路由列表
     */
    public static List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(Objects.equals(0, menu.getVisible()));
            router.setName(getRouteName(menu));
            router.setMenuType(menu.getMenuType());
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            //router.setRedirect(getComponent(menu));
            router.setQuery(menu.getQuery());
            router.setMeta(createMetaVo(menu));
            List<SysMenu> cMenus = menu.getChildren();

            if (!cMenus.isEmpty() && EnumConstant.TYPE_DIR.equals(menu.getMenuType())) {
                if(!isInnerLink(menu)){
                    router.setAlwaysShow(true);
                    router.setRedirect("noRedirect");
                    router.setChildren(buildMenus(cMenus));
                }


            } else if (isMenuFrame(menu)) {
                /*router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(getComponent(menu));
                children.setName(StringTool.capitalize(menu.getPath()));
                children.setMeta(createMetaVo(menu));
                children.setQuery(menu.getQuery());
                childrenList.add(children);
                router.setChildren(childrenList);*/
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setMenuType(menu.getMenuType());
                children.setComponent(getComponent(menu));
                children.setName(StringTool.capitalize(menu.getPath()));
                children.setMeta(createMetaVo(menu));
                children.setQuery(menu.getQuery());
                routers.add(children);
                continue;
            } else if (menu.getParentId().intValue() == 0 && isInnerLink(menu)) {
                MetaVo vo = new MetaVo(menu.getMenuName(), menu.getIcon());
                vo.setAffix(Objects.equals(menu.getAffix(),1));
                router.setMeta(vo);
                router.setPath("/");
                List<RouterVo> childrenList = new ArrayList<RouterVo>();
                RouterVo children = new RouterVo();
                String routerPath = innerLinkReplaceEach(menu.getPath());
                children.setPath(routerPath);
                children.setMenuType(menu.getMenuType());
                //children.setComponent(EnumConstant.INNER_LINK);
                children.setName(StringTool.capitalize(routerPath));
                MetaVo v2 = new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getPath());
                v2.setAffix(Objects.equals(menu.getAffix(),1));
                children.setMeta(v2);
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    private static MetaVo createMetaVo(SysMenu menu){
        MetaVo vo = new MetaVo(menu.getMenuName(), menu.getIcon(), Objects.equals(1, menu.getIsCache()), menu.getPath());
        vo.setAffix(Objects.equals(1,menu.getAffix()));
        if(Objects.equals(menu.getParentId(),0L) && EnumConstant.TYPE_DIR.equals(menu.getMenuType())){
            vo.setBreadcrumb(true);
        }
        return vo;
    }

    /**
     * 获取路由名称
     *
     * @param menu 菜单信息
     * @return 路由名称
     */
    private static String getRouteName(SysMenu menu) {
        String routerName = StringTool.capitalize(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu))
        {
            routerName = StringTool.EMPTY;
        }
        return routerName;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    private static String getRouterPath(SysMenu menu)
    {
        String routerPath = menu.getPath();
        // 内链打开外网方式
        if (menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            routerPath = innerLinkReplaceEach(routerPath);
        }
        // 非外链并且是一级目录（类型为目录）
        if (0 == menu.getParentId().intValue() && EnumConstant.TYPE_DIR.equals(menu.getMenuType())
                && EnumConstant.NO_FRAME.equals(menu.getIsFrame()))
        {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu))
        {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 获取组件信息
     *
     * @param menu 菜单信息
     * @return 组件信息
     */
    /*private static String getComponent(SysMenu menu)
    {
        String component = EnumConstant.LAYOUT;
        if (StringTool.isNotEmpty(menu.getComponent()) && EnumConstant.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(EnumConstant.NO_FRAME)) {
            component = menu.getComponent();
        }
        return component;
    }*/
    public static String getComponent(SysMenu menu) {
        String component = EnumConstant.LAYOUT;
        if (StringTool.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu))
        {
            component = menu.getComponent();
        }
        else if (StringTool.isEmpty(menu.getComponent()) && menu.getParentId().intValue() != 0 && isInnerLink(menu))
        {
            component = EnumConstant.INNER_LINK;
        }
        else if (StringTool.isEmpty(menu.getComponent()) && isParentView(menu))
        {
            component = EnumConstant.PARENT_VIEW;
        }
        return component;
    }

    /**
     * 是否为菜单内部跳转
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private static boolean isMenuFrame(SysMenu menu)
    {
        return menu.getParentId().intValue() == 0 && EnumConstant.TYPE_MENU.equals(menu.getMenuType())
                && menu.getIsFrame().equals(EnumConstant.NO_FRAME);
    }

    /**
     * 是否为内链组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private static boolean isInnerLink(SysMenu menu)
    {
        return menu.getIsFrame().equals(EnumConstant.NO_FRAME) && StringTool.isHttp(menu.getPath());
    }

    /**
     * 是否为parent_view组件
     *
     * @param menu 菜单信息
     * @return 结果
     */
    private static boolean isParentView(SysMenu menu)
    {
        return menu.getParentId().intValue() != 0 && EnumConstant.TYPE_DIR.equals(menu.getMenuType());
    }


    /**
     * 内链域名特殊字符替换
     *
     * @return 替换后的内链域名
     */
    private static String innerLinkReplaceEach(String path) {
        return StringTool.replaceEach(path, new String[] { StringTool.HTTP, StringTool.HTTPS, StringTool.WWW, "." },
                new String[] { "", "", "", "/" });
    }

    public static void formatMenu(SysMenu menu){
        if(Objects.equals(EnumConstant.YES_FRAME,menu.getIsFrame())){
            menu.setPerVal(null);
            menu.setComponent(null);
        }
        if(!Objects.equals(EnumConstant.TYPE_MENU,menu.getMenuType())){
            menu.setComponent(null);
            menu.setQuery(null);
        }
        if(Objects.equals(EnumConstant.TYPE_DIR,menu.getMenuType())){
            menu.setPerVal(null);
            menu.setComponent(null);
            menu.setQuery(null);
        }
        if(Objects.equals(EnumConstant.TYPE_INTF,menu.getMenuType())){
            menu.setPerVal(null);
            menu.setComponent(null);
            //menu.setPath(null);
            menu.setIcon(null);
            menu.setQuery(null);
        }
        if(Objects.equals(EnumConstant.TYPE_BUTTON,menu.getMenuType())){
            menu.setComponent(null);
            menu.setPath(null);
            menu.setIcon(null);
            menu.setQuery(null);
        }

    }


    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private static void recursionFn(List<SysMenu> list, SysMenu t)
    {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private static List<SysMenu> getChildList(List<SysMenu> list, SysMenu t)
    {
        List<SysMenu> tlist = new ArrayList<>();
        for (SysMenu n : list) {
            if (n.getParentId().longValue() == t.getMenuId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private static boolean hasChild(List<SysMenu> list, SysMenu t)
    {
        return getChildList(list, t).size() > 0;
    }


    public static boolean isIgnoreUrl(String url){
        return ignorePattern.matcher(url).matches();
    }

    public static final Pattern dynamicPattern = Pattern.compile("\\{[^\\{\\}\\/]+\\}");
    public static final Pattern ignorePattern = Pattern.compile(".*\\.(css|js|json|html)");

    public static MenuUrlPattern getDynamicUrlPattern(SysMenu menu){
        String url = menu.getPath();
        if(!url.startsWith("/")){
            url = "/" + url;
        }
        int index ;
        if((index = url.indexOf("?")) != -1){
            url = url.substring(0,index);
        }
        MenuUrlPattern p = new MenuUrlPattern();
        p.setMenuId(menu.getMenuId());
        p.setMenuName(menu.getMenuName());
        p.setOriginUrl(url);
        Matcher matcher = dynamicPattern.matcher(url);
        if (matcher.find()){
            url = matcher.replaceAll("[^\\/]*");
            url = url.replace("/","\\/");
            p.setPattern(Pattern.compile(url));
        }
        return p;
    }

    public static void main(String[] args) {
        /*MenuUrlPattern p1 = getDynamicUrlPattern("/home/{userId}");
        if(p1 != null){
            System.out.println(p1.matcher("/home/1").matches());
        }*/
    }
}
